<?php
class Model_Medialib extends Model{

    protected static $_instance =  null;
	/**
     * @return Model_Medialib
     */
	static public function getInstance(){
        if(is_null(self::$_instance))	
           self::$_instance = new self('medialib');     
        return self::$_instance;   
    } 
    /**
     * Get item record by its path
     * @param string $path
     * @param array $fields - optional
     * @return array
     */
    public function getIdByPath($path){
         $recId = $this->_db->fetchOne(
              $this->_db->select()
                        ->from($this->table() , array('id'))
                        ->where('`path` =?', $path)
         );
         return intval($recId);            
    }
    /**
     * Add media item
     * @param string $name
     * @param string $path
     * @param integer $size (bytes)
     * @param string $type
     * @param string $ext  - extension
     * @return integer
     */
    public function addItem($name , $path , $size , $type, $ext)
    {
        $size = number_format(($size/1024/1024) , 3);
        
        $data = array(
            'title'=>$name,
            'path'=>$path,
            'size'=>$size,
            'type'=>$type,
            'user_id'=>User_Admin::getInstance()->id,
            'ext'=>$ext,
            'date'=>date('Y-m-d H:i:s')
        );
        
        $obj = new Db_Object($this->_name);
		$obj->setValues($data);
		        
        if($obj->save()){
            return $this->getIdByPath($path);
        } else{
            return false;
        }   
    }
    /**
     * Delete item from library
     * @param integer $id
     */
    public function remove($id , $log=true){
        if(!$id)
            return false;
            
		$obj = new Db_Object($this->_name, $id);
        $data = $obj->getData();
        if(empty($data))
            return false;

        $docRoot = $this->_storage->get('config_main')->get('docroot');  
            
        if(strlen($data['path']))
        {
             @unlink($docRoot . $data['path']);
             if($data['type'] == 'image'){
                     $conf = $this->getConfig()->__toArray();
                     foreach ($conf['image']['sizes'] as $k=>$v){
                          @unlink($docRoot . self::getImgPath($data['path'],$data['ext'], $k));
                     }
              }  
        }
		$obj->delete();
        return true;  
    }
	/**
     * Calculate image path
     * @param string $path
     * @param string $ext
     * @param string $type
     * @return string
     */
    static public function getImgPath($path, $ext , $type){
        return str_replace($ext, '-' . $type.$ext, $path);
    }
	/**
	 * Add author selection join to the query.
	 * Used with rev_control objects
	 * @param Zend_Db_Select $sql
	 * @param string $fieldAlias
	 * @return void
	 */
	protected function _queryAddAuthor(Zend_Db_Select $sql , $fieldAlias)
	{
		$sql->joinLeft(
			array('u1' => $this->_dbPrefix . 'user') ,
			'user_id = u1.id' ,
			array($fieldAlias => 'u1.name')
		);
	}
    /**
     * Update media item
     * @param integer $id
     * @param array $data
     * @return boolean
     */
    public function update($id ,array $data)
    {
        if(!$id)
            return false;
         
        try{
        	$obj = new Db_Object($this->_name, $id);
        	$obj->setValues($data);
        	$obj->save();
            $hLog = Model_Historylog::getInstance();
            $hLog->log(User_Admin::getInstance()->id,$id,Model_Historylog::Update , $this->table()); 
            return true;
        }catch (Exception $e){
            return false;
        }    
    }
    /**
     * Include required sources
     */
    public function includeScripts()
    {
        $conf = $this->getConfig()->__toArray();
        $resource = Resource::getInstance();
        
        $resource->addCss('/js/lib/ext_ux/css/fileuploadfield.css');
        $resource->addCss('/js/lib/jquery.Jcrop.css');
	    $resource->addCss('/js/lib/uploadify/uploadify.css');
	    
	    $resource->addJs('/js/lib/uploadify/swfobject.js',1,true);
	    $resource->addJs('/js/lib/uploadify/jquery.uploadify.v2.1.4.min.js',1,true);
	    $resource->addJs('/js/app/system/SearchPanel.js',1);
	    $resource->addJs('/js/app/system/ImageField.js',1);
	    $resource->addJs('/js/app/system/MedialinkField.js'  , 1);
        $resource->addJs('/js/app/system/MedialibPanel.js'  , 2);
        $resource->addJs('/js/app/system/medialib/EditWindow.js'  , 3);
        $resource->addJs('/js/app/system/medialib/CropWindow.js'  , 3);
        $resource->addJs('/js/app/system/medialib/HtmlPanel.js'  , 3);
        $resource->addJs('/js/lib/jquery.Jcrop.min.js', 1,true);
        
        $resource->addInlineJs('
        	app.sid="'.session_name().'";
        	app.maxFileSize = "'.ini_get('upload_max_filesize').'";
        	app.mediaConfig = '.json_encode($conf).';
        	app.imageSize = '.json_encode($conf['image']['sizes']).';
        ');
        
    }
	/**
	 * 
	 * @param array $types
	 * @return int
	 */
    public function resizeImages($types = false){
        $data = Model_Medialib::getInstance()->getListVc(false , array('type'=>'image'),false,array('path' , 'ext'));
        ini_set('max_execution_time' , 18000);
        ini_set('ignore_user_abort' ,'On');
        ini_set('memory_limit', '384M');
        
        $conf = $this->getConfig()->__toArray();
        
        $thumbSizes = $conf['image']['sizes'];
        $count =0;
        
         foreach ($data as $v)
         {
            $path = DOC_ROOT.$v['path'];
            if(!file_exists($path))
                continue;
        
            if($types && is_array($types))
            { 
                   foreach ($types as $typename)
                   {
                       if(isset($thumbSizes[$typename]))
                       {
                            $saveName = str_replace($v['ext'], '-'.$typename.$v['ext'], $path);
                           
                            if($conf['image']['thumb_types'][$typename] == 'crop'){
                                Image_Resize::resize($path, $thumbSizes[$typename][0], $thumbSizes[$typename][1],$saveName, true,true);
                            } else{ 
                                Image_Resize::resize($path, $thumbSizes[$typename][0], $thumbSizes[$typename][1],$saveName, true,false);
                            }
                           
                       }
                   }                 
            }else{
                foreach ($thumbSizes as $k=>$item){
                    $saveName = str_replace($v['ext'], '-'.$k.$v['ext'], $path);
                    if($conf['image']['thumb_types'][$typename] == 'crop'){
                            Image_Resize::resize($path, $item[0], $item[1], $saveName, true,true);
                    } else{ 
                            Image_Resize::resize($path, $item[0], $item[1], $saveName, true,false);
                    }
                }
            }    
            $count ++;
        }
        return $count;
    }
    /**
     * Crop image and create thumbs
     * @param array $srcData  - media library record
     * @param integer $x
     * @param integer $y
     * @param integer $w
     * @param integer $h
     */
    public function cropAndResize($srcData , $x,$y,$w,$h , $type){
        ini_set('max_execution_time' , 18000);
        ini_set('memory_limit', '384M');
        $docRoot = $this->_storage->get('config_main')->get('docroot');
        $conf = $this->getConfig()->__toArray();
        $thumbSizes = $conf['image']['sizes'];  
        $path = $docRoot.$srcData['path'];
        
        if(!file_exists($path))
           false;
             
        $tmpPath = $docRoot . '/media/tmp/'.basename($path);
    
        Image_Resize::cropImage($path, $tmpPath , $x, $y, $w, $h);
        
        if(!isset($thumbSizes[$type]))
            return false;
            
        $saveName = str_replace($srcData['ext'], '-'.$type.$srcData['ext'], $path);  
        if(!Image_Resize::resize($tmpPath, $thumbSizes[$type][0], $thumbSizes[$type][1], $saveName, true,false))
        	return false;

        unlink($tmpPath);
        return true;
    }
    /**
     * Update modification date
     * @param integer $id
     * @return void
     */
    public function updateModifyDate($id){
    	$obj = new Db_Object($this->_name, $id);
        $obj->set('modified', date('Y-m-d h:i:s'));
        $obj->save();
    }
    /**
     * Mark object as hand croped
     * @param integer $id
     * @return void
     */
    public function markCroped($id){
   		$obj = new Db_Object($this->_name, $id);
   		$obj->set('croped', 1);
        $obj->save();
    }
    /**
     * Get media library config
     * @return Config_File_Array
     */
    public function getConfig(){
        $docRoot = $this->_storage->get('config_main')->get('docroot');
        return Config::factory(Config::File_Array, $docRoot.'/system/config/media_library.php');
    }
}